/**
 ** @author:	   浓咖啡
 ** @date:	   2017.3.29
 ** @brief:      主程序,使用raw模式注意看raw.c注释
 */

#include <string.h>
#include <getopt.h>
#include "cap_manager.h"

void help(char *progname)
{
    fprintf(stderr, "-----------------------------------------------------------------------\n");
    fprintf(stderr, "Usage: %s\n" \
            "-c | --choose cap \"<cap_name>\"\n" \
            "-d | --dev \"<dev_name>\"\n" \
            "-f | --filter \"<net filter>\"\n", progname);
    fprintf(stderr, "-----------------------------------------------------------------------\n");
    fprintf(stderr, "Example:\n" \
            " To use pcap and open \"eth0\" and filter \"port 8888\":\n" \
            " %s -c \"pcap\" -d \"eth0\" -f \"port 8888\"\n"
            "but raw capture does not support filter\n\n", progname);
}

/**
 * 运行./pcap -h查看帮助文档
 */
int main(int argc, char *argv[])
{
    char *dev  = NULL;
    char *filter = NULL;
    char *cap_fun = "pcap";

    while(1) {
        int option_index = 0, c=0;
        static struct option long_options[] = \
        {
            {"h", no_argument, 0, 0},
            {"help", no_argument, 0, 0},
            {"d", required_argument, 0, 0},
            {"f", required_argument, 0, 0},
            {"c", required_argument, 0, 0},
            {0, 0, 0, 0}
        };

        c = getopt_long_only(argc, argv, "", long_options, &option_index);

        /* no more options to parse */
        if (c == -1){
            break;
        }
        /* unrecognized option */
        if(c=='?'){
            help(argv[0]);
            return 0;
        }

        switch (option_index) {
        /* h, help */
        case 0:
        case 1:
            help(argv[0]);
            return 0;
            break;

            /* d, dev */
        case 2:
            dev = strdup(optarg);
            break;

        case 3:
            filter = strdup(optarg);
            break;

        case 4:
            cap_fun = strdup(optarg);
            break;

        default:
            help(argv[0]);
            return 0;
        }
    }

    if(cap_init()){
        printf("cap_init err\n");
        exit(-1);
    }

    if(init_cap(cap_fun, dev, filter)){
        printf("init_cap err\n");
        exit(-1);
    }

    start_cap();

    close_cap();

    return 0;
}
